package com.sys.basics.filter.shiro;

import cn.hutool.json.JSONUtil;
import com.sys.basics.config.jsonRes.JsonResult;
import org.apache.shiro.SecurityUtils;
import org.springframework.http.HttpStatus;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class SessionFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
            throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        // 判断 session 里是否有用户信息
        if (!SecurityUtils.getSubject().isAuthenticated()) {
            // 在响应头设置session状态
            response.setContentType("application/json; charset=utf-8");
            response.setCharacterEncoding("UTF-8");
            response.setStatus(HttpStatus.FORBIDDEN.value());
            PrintWriter out = response.getWriter();
            JsonResult result = new JsonResult();
            result.setCode(String.valueOf(HttpStatus.FORBIDDEN.value()));
            result.setMessage("SESSION过期");
            out.println(JSONUtil.parseObj(result, false));
            out.flush();
            return;
        }
        filterChain.doFilter(request, servletResponse);
    }
}
